package ext.tianma.util;

import java.beans.PropertyVetoException;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.log4j.Logger;

import wt.content.ApplicationData;
import wt.content.ContentHelper;
import wt.content.ContentHolder;
import wt.content.ContentServerHelper;
import wt.content.FormatContentHolder;
import wt.util.WTException;
import wt.util.WTProperties;

/**
 * 文件下载通用类
 * 
 * @author lilin
 *
 */
public class FileDownloadUtil {
	private static String templateFolder = null;
	public static String FolderPath;
	private static Logger logger = Logger.getLogger(FileDownloadUtil.class);
	static {
		try {
			templateFolder = WTProperties.getLocalProperties().getProperty("wt.home");
			FolderPath = templateFolder + File.separator + "codebase" + File.separator + "temp";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 创建文件夹
	 * 
	 * @param diskPath
	 * @return
	 */
	public static String createDiskForder(String diskPath) {
		File file = new File(diskPath);
		if (!file.exists()) {// 如果文件夹不存在
			file.mkdirs();// 创建文件夹
		}
		return diskPath;
	}

	/**
	 * 下载主文件
	 * 
	 * @param contentHolder
	 * @param FolderName
	 * @return
	 * @throws WTException
	 */
	public static boolean downloadPrimaryFile(ContentHolder contentHolder, String FolderName, String fileName)
			throws WTException {

		String tempFolderPath = FolderPath + File.separator + "PrimaryFileTemp" + File.separator + FolderName;// 文件夹
		tempFolderPath = createDiskForder(tempFolderPath);
		FormatContentHolder aFormatContentHolder = null;
		boolean rtnValue = true;
		if (contentHolder == null) {
			return false;
		}
		try {
			aFormatContentHolder = (FormatContentHolder) ContentHelper.service.getContents(contentHolder);
		} catch (PropertyVetoException e1) {
			e1.printStackTrace();
		}
		ApplicationData primary = (ApplicationData) ContentHelper.getPrimary(aFormatContentHolder);
		if (primary != null) {
			try {
				if (!"".equals(fileName) || fileName != null) {
					tempFolderPath = tempFolderPath + File.separator + fileName + "_" + primary.getFileName();
				}
				ContentServerHelper.service.writeContentStream(primary, tempFolderPath);
			} catch (IOException e) {
				logger.info("写文件错误" + tempFolderPath);
				rtnValue = false;
			}
		} else {
			rtnValue = false;
		}

		return rtnValue;
	}

	/**
	 * 将存放在sourceFilePath目录下的源文件，打包成fileName名称的zip文件，并存放到zipFilePath路径下
	 * 
	 * @param sourceFilePath
	 *            :待压缩的文件路径
	 * @param zipFilePath
	 *            :压缩后存放路径
	 * @param fileName
	 *            :压缩后文件的名称
	 * @return
	 */
	public static boolean fileToZip(String sourceFilePath, String zipFilePath, String fileName) {
		boolean flag = false;
		File sourceFile = new File(sourceFilePath);
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		ZipOutputStream zos = null;

		if (sourceFile.exists() == false) {
			logger.info("待压缩的文件目录：" + sourceFilePath + "不存在.");
		} else {
			try {
				File zipFile = new File(zipFilePath + File.separator + fileName + ".zip");
				boolean flagTemp = false;
				if (zipFile.exists()) {
					// logger.info(zipFilePath + "目录下存在名字为:" + fileName + ".zip" + "打包文件.");
					if (zipFile.delete()) {
						flagTemp = true;
					}
				} else {
					flagTemp = true;
				}
				if (flagTemp) {
					File[] sourceFiles = sourceFile.listFiles();
					if (null == sourceFiles || sourceFiles.length < 1) {
						logger.info("待压缩的文件目录：" + sourceFilePath + "里面不存在文件，无需压缩.");
					} else {
						fos = new FileOutputStream(zipFile);
						zos = new ZipOutputStream(new BufferedOutputStream(fos));
						byte[] bufs = new byte[1024 * 10];
						for (int i = 0; i < sourceFiles.length; i++) {
							// 创建ZIP实体，并添加进压缩包
							ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
							zos.putNextEntry(zipEntry);
							// 读取待压缩的文件并写进压缩包里
							fis = new FileInputStream(sourceFiles[i]);
							bis = new BufferedInputStream(fis, 1024 * 10);
							int read = 0;
							while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
								zos.write(bufs, 0, read);
							}
							bis.close();
							fis.close();
						}
						flag = true;
					}
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} finally {
				// 关闭流
				try {
					if (null != zos)
						zos.close();
					if (null != fos)
						fos.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
		}
		return flag;
	}

	/**
	 * 删除空目录
	 * 
	 * @param dir
	 *            将要删除的目录路径
	 */
	public static void doDeleteEmptyDir(String dir) {
		boolean success = (new File(dir)).delete();
		if (success) {
			logger.info("Successfully deleted empty directory: " + dir);
		} else {
			logger.info("Failed to delete empty directory: " + dir);
		}
	}

	/**
	 * 递归删除目录下的所有文件及子目录下所有文件
	 * 
	 * @param dir
	 *            将要删除的文件目录
	 * @return boolean Returns "true" if all deletions were successful. If a
	 *         deletion fails, the method stops attempting to delete and returns
	 *         "false".
	 */
	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// 目录此时为空，可以删除
		return dir.delete();
	}

	public static void main(String[] args) throws InterruptedException {
		String path = "E:\\常用文档\\天马\\C10\\需求文档 - 副本";
		String zippath = "E:\\常用文档\\天马\\C10";
		// if (FileDownloadUtil.fileToZip(path, zippath, "需求文档")) {
		// logger.info("okkkkkk");
		// boolean success = deleteDir(new File(path));
		// if (success) {
		// logger.info("ok");
		// }
		// }

		// Thread.currentThread();
		// Thread.sleep(20000);
		// boolean success = deleteDir(new File(path));
		// if (success) {
		// logger.info("ok");
		// }

		// logger.info("path=========" + otherPath);
		// otherPath = createDiskForder(otherPath);
		// logger.info("path=========" + otherPath);
	}
}
